<?php
namespace App\Api\Fcjd;

use PhalApi\Api;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;


/**
 * 获取下级代理总数接口
 * @desc 读取phone_kami表数据
 */
class UserKamiTj extends Api {
    public function getRules() {
        return array(
            'getByMonth' => array(
                'username' => array('name' => 'username', 'type' => 'string', 'require' => true, 'desc' => 'username'),
                'month' => array('name' => 'month', 'type' => 'string', 'require' => true, 'desc' => 'month'),
            ),
            'getByMonthXlsx' => array(
                'username' => array('name' => 'username', 'type' => 'string', 'require' => true, 'desc' => 'username'),
                'month' => array('name' => 'month', 'type' => 'string', 'require' => true, 'desc' => 'month'),
            ),
        );
    }

    /**
     * getByMonth数据
     * @desc 获取phone_kami表数据
     * @return array items 数据列表
     * @return int total 总记录数
     */
    public function getByMonth() {

        $where_self = array('username' => $this->username, 'used_time LIKE ?' => '%' . $this->month . "%");

        $self = \PhalApi\DI()->notorm
            ->phone_kami_used
            ->where($where_self)
            ->select('card_code,used_time,nickname,user_id,phone_id,duration_type')
            ->fetchAll();

        $where_agent = array(
            'Invitations LIKE ?' => '%' . $this->username . "%",
            'used_time LIKE ?' => '%' . $this->month . "%",
        );
        $Agent = \PhalApi\DI()->notorm
            ->phone_kami_used
            ->where($where_agent)
            ->select('card_code,used_time,nickname,user_id,phone_id,duration_type')
            ->fetchAll();

        // 合并两个已查询出的数组
        $combinedResult = array_merge($self, $Agent);
        return $combinedResult;
    }



    /**
     * getByMonth数据表格
     * @desc 获取phone_kami表数据并生成Excel表格下载链接
     * @return array 返回Excel文件下载链接
     */
    public function getByMonthXlsx() {

        // 获取数据
        $where_self = array('username' => $this->username, 'used_time LIKE ?' => '%' . $this->month . "%");

        $self = \PhalApi\DI()->notorm
            ->phone_kami_used
            ->where($where_self)
            ->select('card_code,used_time,nickname,user_id,phone_id,duration_type,username,mobile')
            ->fetchAll();

        $where_agent = array(
            'Invitations LIKE ?' => '%' . $this->username . "%",
            'used_time LIKE ?' => '%' . $this->month . "%",
        );
        $Agent = \PhalApi\DI()->notorm
            ->phone_kami_used
            ->where($where_agent)
            ->select('card_code,used_time,nickname,user_id,phone_id,duration_type,username,mobile')
            ->fetchAll();

        // 合并两个已查询出的数组
        $combinedResult = array_merge($self, $Agent);

        // 生成文件名
        $filename = '卡密使用记录_' . $this->month . '.csv';
        
        // 使用绝对路径
        $uploadDir = '/www/wwwroot/api.wenfree.cn/phalapi/public/excel/';
        
        // 确保目录存在
        if (!file_exists($uploadDir)) {
            mkdir($uploadDir, 0777, true);
        }

        // 文件路径
        $filepath = $uploadDir . $filename;

        // 打开文件
        $fp = fopen($filepath, 'w');
        if ($fp === false) {
            throw new \Exception('无法创建文件：' . $filepath);
        }

        // 写入 UTF-8 BOM
        fprintf($fp, chr(0xEF).chr(0xBB).chr(0xBF));

        // 写入表头
        fputcsv($fp, ['卡密', '使用时间', '昵称', '中控号', '使用手机号','用户ID', '手机ID', '套餐时长']);

        // 写入数据
        foreach ($combinedResult as $item) {
            fputcsv($fp, [
                $item['card_code'],
                $item['used_time'],
                $item['nickname'],
                $item['username'],
                $item['mobile'],
                $item['user_id'],
                $item['phone_id'],
                $item['duration_type']
            ]);
        }

        // 关闭文件
        fclose($fp);

        // 生成下载链接 (使用相对路径)
        $downloadUrl = '/excel/' . $filename;

        // 设置成功响应
        \PhalApi\DI()->response->setMsg('CSV文件生成成功');
        \PhalApi\DI()->response->setRet(200);

        return array(
            'download_url' => "http://api.wenfree.cn".$downloadUrl,
            'filename' => $filename,
            'total_records' => count($combinedResult),
            'file_path' => $filepath // 添加文件路径到返回数据，方便调试
        );
    }
    
    
}